import {getDictDataList, getDictTypePage} from '@/services/system/dict';
import {useState, useCallback} from 'react';
import {message} from 'antd';

interface DictType {
  dictName: string;
  dictType: string;
  id: string;
  status: string;
}

interface DictData {
  dictLabel: string;
  dictValue: string;
  dictType: string;
  status: string;
  isDefault: string;
  dictSort: number;
  color: string;
}

export default () => {
  const [dictTypes, setDictTypes] = useState<DictType[]>([]);
  const [dictData, setDictData] = useState<Record<string, DictData[]>>({});
  const [loading, setLoading] = useState<Record<string, boolean>>({});

  // 加载字典类型
  const loadDictTypes = useCallback(async () => {
    try {
      if (dictTypes.length === 0) {
        setLoading({...loading, types: true});
        const response = await getDictTypePage({
          pageSize: 100,
          current: 1,
        });
        if (response.success) {
          const activeTypes = response.data.data.filter((item: DictType) => item.status === '0');
          setDictTypes(activeTypes);
          return activeTypes;
        }
        message.error('获取字典类型失败');
      }
      return dictTypes;
    } catch (error) {
      message.error('加载字典类型出错');
      return [];
    } finally {
      setLoading({...loading, types: false});
    }
  }, [dictTypes, loading]);

  // 加载字典数据
  const loadDictData = useCallback(async (dictType: string) => {
    try {
      if (!dictData[dictType]) {
        setLoading({...loading, [dictType]: true});
        const response = await getDictDataList({dictType});
        if (response.success) {
          const formattedData = response.data
            .filter((item: DictData) => item.status === '0')
            .sort((a: DictData, b: DictData) => a.dictSort - b.dictSort)
            .map((item: DictData) => ({
              label: item.dictLabel,
              value: item.dictValue,
              color: item.color,
            }));

          setDictData(prev => ({
            ...prev,
            [dictType]: formattedData
          }));
          return formattedData;
        }
        message.error('获取字典数据失败');
        return [];
      }
      return dictData[dictType] || [];
    } catch (error) {
      message.error('加载字典数据出错');
      return [];
    } finally {
      setLoading({...loading, [dictType]: false});
    }
  }, [dictData, loading]);

  // 清除缓存
  const clearCache = useCallback(() => {
    setDictData({});
    setDictTypes([]);
    setLoading({});
  }, []);

  // 获取加载状态
  const getLoading = useCallback((key: string) => {
    return loading[key] || false;
  }, [loading]);

  return {
    dictTypes,
    dictData,
    loading,
    loadDictTypes,
    loadDictData,
    clearCache,
  };
};
